package pannel.recipe;

import system.BasePage;
import pannel.user.User;
import pannel.category.Category;
import pannel.category.CategoryDao;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.time.format.DateTimeFormatter;

public class RecipeManagementPage extends BasePage {
    private DefaultTableModel model;
    private List<Recipe> recipeList = new ArrayList<>();
    private JTable table;
    private JTextField searchField;
    private JComboBox<Category> categoryComboBox;
    private int currentPage = 1;
    private int pageSize = 10;
    private JLabel pageInfoLabel;
    private RecipeDao recipeDao;
    private CategoryDao categoryDao;
    private int totalRecords = 0;
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public RecipeManagementPage(User user) {
        super(user);
        this.recipeDao = new RecipeDao();
        this.categoryDao = new CategoryDao();
        initPageContent();
    }

    @Override
    protected void initPageContent() {
        setPageTitle("菜谱管理");
        setupContent();
        refreshTable();
    }

    private void setupContent() {
        contentArea.setLayout(new BorderLayout());
        JPanel topPanel = new JPanel(new BorderLayout());

        // 搜索面板
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        searchField = new JTextField(20);
        categoryComboBox = new JComboBox<>();
        
        // 确保在这里初始化分类数据
        try {
            loadCategories();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "加载分类数据失败：" + e.getMessage());
        }

        JButton searchButton = new JButton("搜索");
        searchPanel.add(new JLabel("菜谱名称："));
        searchPanel.add(searchField);
        searchPanel.add(new JLabel("分类："));
        searchPanel.add(categoryComboBox);
        searchPanel.add(searchButton);

        // 工具栏
        JPanel toolBar = new JPanel(new FlowLayout(FlowLayout.LEFT));
        toolBar.setBackground(Color.WHITE);

        JButton addButton = new JButton("新增菜谱");
        JButton deleteButton = new JButton("删除菜谱");
        JButton editButton = new JButton("编辑菜谱");

        toolBar.add(addButton);
        toolBar.add(deleteButton);
        toolBar.add(editButton);

        topPanel.add(searchPanel, BorderLayout.NORTH);
        topPanel.add(toolBar, BorderLayout.CENTER);

        // 表格设置
        String[] columnNames = {"ID", "菜谱名称", "分类", "描述", "创建时间", "图片"};
        model = new DefaultTableModel(new Object[0][], columnNames) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
            
            @Override
            public Class<?> getColumnClass(int columnIndex) {
                if (columnIndex == 5) return ImageIcon.class;
                return super.getColumnClass(columnIndex);
            }
        };
        
        table = new JTable(model);
        table.getTableHeader().setReorderingAllowed(false);
        table.setRowHeight(60); // 设置行高以适应图片
        
        // 设置图片列的渲染器
        table.getColumnModel().getColumn(5).setCellRenderer(new ImageRenderer());

        // 分页面板
        JPanel paginationPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JButton prevButton = new JButton("上一页");
        JButton nextButton = new JButton("下一页");
        pageInfoLabel = new JLabel();

        paginationPanel.add(prevButton);
        paginationPanel.add(pageInfoLabel);
        paginationPanel.add(nextButton);

        // 按钮事件处理
        prevButton.addActionListener(e -> {
            if (currentPage > 1) {
                currentPage--;
                refreshTable();
            }
        });

        nextButton.addActionListener(e -> {
            int totalPages = (int) Math.ceil((double) totalRecords / pageSize);
            if (currentPage < totalPages) {
                currentPage++;
                refreshTable();
            }
        });

        searchButton.addActionListener(e -> {
            currentPage = 1;
            refreshTable();
        });

        addButton.addActionListener(e -> {
            RecipeDialog dialog = new RecipeDialog(null, "新增菜谱", null);
            if (dialog.showDialog()) {
                try {
                    Recipe newRecipe = Recipe.builder()
                            .name(dialog.getRecipeName())
                            .description(dialog.getDescription())
                            .categoryId(dialog.getSelectedCategory().getId())
                            .imagePath(dialog.getImagePath())
                            .build();

                    if (recipeDao.insert(newRecipe)) {
                        JOptionPane.showMessageDialog(this, "添加菜谱成功！");
                        refreshTable();
                    } else {
                        JOptionPane.showMessageDialog(this, "添加菜谱失败！");
                    }
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(this, "添加菜谱失败：" + ex.getMessage());
                }
            }
        });

        deleteButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow != -1) {
                int id = (Integer) table.getValueAt(selectedRow, 0);
                int confirm = JOptionPane.showConfirmDialog(this,
                        "确定要删除该菜谱吗？", "确认删除",
                        JOptionPane.YES_NO_OPTION);

                if (confirm == JOptionPane.YES_OPTION) {
                    try {
                        if (recipeDao.deleteById(id)) {
                            JOptionPane.showMessageDialog(this, "删除成功！");
                            refreshTable();
                        } else {
                            JOptionPane.showMessageDialog(this, "删除失败！");
                        }
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(this, "删除失败：" + ex.getMessage());
                    }
                }
            } else {
                JOptionPane.showMessageDialog(this, "请选择要删除的菜谱");
            }
        });

        editButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow != -1) {
                Recipe selectedRecipe = recipeList.get(selectedRow);
                RecipeDialog dialog = new RecipeDialog(null, "编辑菜谱", selectedRecipe);
                if (dialog.showDialog()) {
                    try {
                        selectedRecipe.setName(dialog.getRecipeName());
                        selectedRecipe.setDescription(dialog.getDescription());
                        selectedRecipe.setCategoryId(dialog.getSelectedCategory().getId());
                        selectedRecipe.setImagePath(dialog.getImagePath());

                        if (recipeDao.updateById(selectedRecipe)) {
                            JOptionPane.showMessageDialog(this, "更新成功！");
                            refreshTable();
                        } else {
                            JOptionPane.showMessageDialog(this, "更新失败！");
                        }
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(this, "更新失败：" + ex.getMessage());
                    }
                }
            } else {
                JOptionPane.showMessageDialog(this, "请选择要编辑的菜谱");
            }
        });

        JScrollPane scrollPane = new JScrollPane(table);
        contentArea.add(topPanel, BorderLayout.NORTH);
        contentArea.add(scrollPane, BorderLayout.CENTER);
        contentArea.add(paginationPanel, BorderLayout.SOUTH);
    }

    private void loadCategories() {
        try {
            if (categoryDao == null) {
                categoryDao = new CategoryDao();
            }
            List<Category> categories = categoryDao.findAll();
            if (categories == null) {
                categories = new ArrayList<>();
            }
            
            DefaultComboBoxModel<Category> model = new DefaultComboBoxModel<>();
            model.addElement(null); // 添加空选项
            for (Category category : categories) {
                model.addElement(category);
            }
            categoryComboBox.setModel(model);
            
            // 设置渲染器来显示分类名称
            categoryComboBox.setRenderer(new DefaultListCellRenderer() {
                @Override
                public Component getListCellRendererComponent(JList<?> list, Object value, 
                        int index, boolean isSelected, boolean cellHasFocus) {
                    if (value == null) {
                        value = "全部分类";
                    } else {
                        value = ((Category) value).getName();
                    }
                    return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                }
            });
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载分类数据失败：" + e.getMessage());
        }
    }

    private void refreshTable() {
        SwingUtilities.invokeLater(() -> {
            try {
                String searchText = searchField.getText().trim();
                Category selectedCategory = (Category) categoryComboBox.getSelectedItem();
                Integer categoryId = selectedCategory != null ? selectedCategory.getId() : null;
                
                recipeList = recipeDao.pageQuery(searchText, categoryId, currentPage, pageSize);
                totalRecords = recipeDao.getTotalCount(searchText, categoryId);

                model.setRowCount(0);
                for (Recipe recipe : recipeList) {
                    model.addRow(new Object[]{
                            recipe.getId(),
                            recipe.getName(),
                            recipe.getCategoryName(),
                            recipe.getDescription(),
                            recipe.getCreateTime().format(DATE_FORMATTER),
                            createScaledImageIcon(recipe.getImagePath())
                    });
                }
                updatePageInfo();
                table.repaint();
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(this, "获取菜谱数据失败：" + e.getMessage());
            }
        });
    }

    private ImageIcon createScaledImageIcon(String path) {
        if (path == null || path.isEmpty()) {
            return createDefaultIcon();
        }
        try {
            ImageIcon originalIcon = new ImageIcon(path);
            Image image = originalIcon.getImage();
            return new ImageIcon(image.getScaledInstance(50, 50, Image.SCALE_SMOOTH));
        } catch (Exception e) {
            return createDefaultIcon();
        }
    }

    private ImageIcon createDefaultIcon() {
        BufferedImage image = new BufferedImage(50, 50, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = image.createGraphics();
        g2d.setColor(Color.LIGHT_GRAY);
        g2d.fillRect(0, 0, 50, 50);
        g2d.dispose();
        return new ImageIcon(image);
    }

    private void updatePageInfo() {
        int totalPages = (int) Math.ceil((double) totalRecords / pageSize);
        pageInfoLabel.setText(String.format("第 %d/%d 页  共%d条记录", currentPage, totalPages, totalRecords));
    }

    private static class ImageRenderer extends DefaultTableCellRenderer {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                     boolean isSelected, boolean hasFocus,
                                                     int row, int column) {
            if (value instanceof ImageIcon) {
                JLabel label = new JLabel((ImageIcon) value);
                label.setHorizontalAlignment(JLabel.CENTER);
                if (isSelected) {
                    label.setBackground(table.getSelectionBackground());
                    label.setOpaque(true);
                }
                return label;
            }
            return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        }
    }
} 